import re
from datetime import datetime

from flask import current_app
from flask import g
from flask import request, jsonify
from flask import session
from info.modules.index import api
from info import constants
from info import db, redis_store
from info.models import User, Area, House, Facility
from info.utils.common import user_login
from info.utils.response_code import RET


@api.route("/session",  methods=["GET","POST", "DELETE"])
@user_login
def login():
    if request.method == "GET":
        if not g.user:
            return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
        else:
            data = {
                "name": g.user.name,
                "user_id": g.user.id
            }
            return jsonify(errno=RET.OK, errmsg="ok", data=data)
    elif request.method == "POST":
        dict_data = request.json
        mobile = dict_data.get("mobile")
        password = dict_data.get("password")

        if not all([mobile, password]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

        if not re.match(r"1[35678]\d{9}", mobile):
            return jsonify(errno=RET.PARAMERR, errmsg="手机号的格式不正确")


        try:
            user = User.query.filter_by(mobile=mobile).first()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

        if not user:
            return jsonify(errno=RET.NODATA, errmsg="用户没有注册")
        # print(password)
        if not user.check_passowrd(password):
            return jsonify(errno=RET.DATAERR, errmsg="密码输入错误")
        # if password != User.password:
        #     return jsonify(errno=RET.DATAERR, errmsg="密码输入错误")

        user.last_login = datetime.now()

        try:
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

        session["user_id"] = user.id

        return jsonify(errno=RET.OK, errmsg="登录成功")
    elif request.method == "DELETE":
        session.pop("user_id", None)
        return jsonify(errno=RET.OK, errmsg="退出成功")


@api.route("/houses", methods=["POST"])
@user_login
def new_houses_release():
    """
    新房源发布
    :return:
    """
    # 以下是地区列表的下拉菜单
    # if request.method == "GET":
        # areas = Area.query.all()
        # areas_dict_li = [area.to_dict()for area in areas]
        #
        # data ={
        #     "areas_dict_li": areas_dict_li
        # }
        # return render_template("/newhouse.html", data=data)
    # if request.method == "POST":
    get_request = request.json

    title = get_request.get("title") # 房屋名称标题
    price = get_request.get("price") # 房屋单价
    area_id = get_request.get("area_id") # 房屋所属地区的编号
    address = get_request.get("address") # 房屋地址
    room_count = get_request.get("room_count") # 房屋包含的房间数目
    acreage = get_request.get("acreage") # 房屋面积
    unit = get_request.get("unit") # 房屋布局(几室几厅)
    capacity = get_request.get("capacity") # 房屋容纳人数
    beds = get_request.get("beds") # 房屋卧双数目
    deposit = get_request.get("deposit") # 押金
    min_days = get_request.get("min_days") # 最小入住天数
    max_days = get_request.get("max_days") # 最大入住天数
    facility = get_request.get("facility")

    if not all([title, price, area_id, address, room_count,
                acreage, unit, capacity, beds, deposit, min_days, max_days, facility]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        price = int(float(price)*100)
        deposit = int(float(deposit)*100)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数类型不正确")
    try:
        area = Area.query.get(area_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if area is None:
        return jsonify(errno=RET.NODATA, errmsg="区县信息有误")
    house = House()
    house.user_id = g.user.id
    house.title = title
    house.price = price
    house.area_id = area_id
    house.address = address
    house.room_count = room_count
    house.acreage = acreage
    house.unit = unit
    house.capacity = capacity
    house.beds = beds
    house.deposit = deposit
    house.min_days = min_days
    house.max_days = max_days
    house.facilities = facility
    # if facility:
    #     try:
    #         facilities = Facility.query.filter(Facility.id.in_(facility_ids)).all()
    #     except Exception as e:
    #         current_app.logger.error(e)
    #         return jsonify(errno=RET.PARAMERR, errmsg="设施参数查询错误")
    try:
        db.session.add(house)
        db.session.commit(house)
    except Exception as e:
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="数据保存失败")

    return jsonify(errno=RET.OK, errmsg="OK", data={"house_id": house.id})